<template>
  <a-card :bordered="false">

    <!-- 操作按钮区域 -->
    <div class="table-operator"  v-if="!dataSource || dataSource.length == 0">
      <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpPurchaseCalibrationDetail:add')" :hidden="disabled || showAdd">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="key"
        :columns="defColumns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="disabled?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <template slot="invitationId" slot-scope="text,record">
          <a @click.prevent="onDetail(record)">
            {{findInvitationId(record.invitationId)}}
          </a>
        </template>

        <span slot="action" slot-scope="text, record">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            @click="handleEdit(record)"
            :hidden="disabled"
            :disabled="isDisabledAuth('erpPurchaseCalibrationDetail:edit')"
          />
          <a-divider type="vertical" :hidden="disabled"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="delete"
              :hidden="disabled"
              :disabled="isDisabledAuth('erpPurchaseCalibrationDetail:delete')"/>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <ErpPurchaseCalibrationDetailModal ref="modalForm" @dataOne="dataOne" @ok="modalFormOk"></ErpPurchaseCalibrationDetailModal>

    <!-- 招标采购申请单据详情开始 -->
    <a-modal
      :maskClosable="false"
      title="招标采购申请单据详情"
      :width="1350"
      :bodyStyle="{
        padding: '0 24px'
      }"
      :visible="visibleDetail"
      @cancel="handleCancelDetail"
      cancelText="关闭">
        <erp-purchase-apply-invitation-form ref="realForm" :disabled="true" normal></erp-purchase-apply-invitation-form>
      <template slot="footer">
        <a-button @click.stop="handleCancelDetail">关闭</a-button>
      </template>
    </a-modal>
    <!-- 招标采购申请单据详情结束 -->

    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
    <SelectPurchaseCalibrationOpinionDetailModal ref="opinionInputModal"></SelectPurchaseCalibrationOpinionDetailModal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import ErpPurchaseCalibrationDetailModal from './ErpPurchaseCalibrationDetailModal'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import AuditModal from '@/views/scy/components/AuditModal'
import { filterObj } from '@/utils/util'
import { getAction } from '@/api/manage'
import Vue from 'vue'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import ErpPurchaseApplyInvitationForm from '@/views/erp/purchase/procurement/modules/ErpPurchaseApplyInvitationForm'
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import SelectPurchaseCalibrationOpinionDetailModal from '../SelectPurchaseCalibrationOpinionDetailModal'
  export default {
    name: 'ErpPurchaseCalitionUnitList',
    mixins: [mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpProjectReportModal,
      ErpPurchaseApplyInvitationForm,
      ErpPurchaseCalibrationDetailModal,
      AuditModal,
      SelectPurchaseCalibrationOpinionDetailModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      teamId: {
        type: String,
        default: '',
        required: false
      }
    },
    data () {
      return {
        params: {
          billId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '采购申请单明细管理页面',
        // 表头
        columns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '关联招标采购申请',
            align: 'center',
            dataIndex: 'invitationId',
            scopedSlots: { customRender: 'invitationId' },
          },
          {
            title:'项目名称',
            align:"center",
            dataIndex: 'projectId',
            customRender: (text,r) => {
              if (!text) {
                return ''
              } else {
                return <a v-on:click={(e) => this.onDetails(text)}>{ filterMultiDictText(this.dictOptions['projectId'], text + '') }</a>;
              }
            }
          },
          {
            title: '团队名称',
            align: 'center',
            dataIndex: 'teamId',
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['teamId'], text + '')
              }
            }
          },
          {
            title: '定标意见单',
            align: 'center',
            dataIndex: 'opinionId',
            customRender: (text,r) => {
              if (!text) {
                return ''
              } else {
                return <a v-on:click={(e) => this.onOpinionDetails(text)}>{ filterMultiDictText(this.dictOptions['opinionId'], text + '') }</a>;
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/purchase/procurement/erpPurchaseCalibrationDetail/allList',
          queryById: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/queryById',
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById'
        },
        dictOptions: {},
        superFieldList: [],
        showAdd: false,
        visibleDetail: false
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      if(this.disabled){
        this.defColumns.pop()
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    computed: {
    },
    watch: {
      // 监听是否有数据
      dataSource: {
        handler (val) {
          // 获取招标采购申请详情
          // const id = this.dataSource[0].invitationId;
          if (val && val.length) {
            // this.getPurchasing(val[0].invitationId)
            const promises = val.map((v) => {
              if(!v.projectBudget){
                return getAction(this.url.queryById, { id:v.invitationId })
              } else {
                return 1
              }
            })
            if(promises.filter(v => v!=1).length){
              Promise.all(promises).then(function (posts) {
                if(posts.length){
                  posts.forEach((cv,index) => {
                    val[index].projectBudget = cv.result.projectBudget
                  })
                }
              })
            }
            let total = 0
            val.forEach(c => {
              total += c.projectBudget
            })
            this.$emit('onBudget', total)
          } else {
            this.$emit('onBudget', null)
          }
        },
        immediate: true
      }
    },
    methods: {
      onDetail(data) {
        this.visibleDetail = true
        this.$nextTick(()=>{
          const id = data.invitationId;
          getAction(this.url.queryById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              this.$refs.realForm.edit(model);
            }
          })
        });
      },
      // 获取招标哦采购申请详情
      getPurchasing (id) {
        getAction(this.url.queryById, { id }).then((res) => {
          if (res.success) {
            this.$emit('onBudget', res.result.projectBudget)
          }
        })
      },
      handleCancelDetail() {
        this.visibleDetail = false
      },
      findInvitationId(text) {
        if (!text) {
          return ''
        } else {
          return filterMultiDictText(this.dictOptions['invitationId'], text + '')
        }
      },
      initDictConfig() {
        // 项目名称
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        //团队名称
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
        //关联招标采购申请
        initDictOptions('erp_purchase_apply_invitation,purchase_bill,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'invitationId', res.result)
          }
        })
        //关联定标意见单
        initDictOptions('erp_purchase_calibration_opinion,purchase_bill,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'opinionId', res.result)
          }
        })
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'provisionSmall', text: '采购小类', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialBillId', text: '物料编号', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialName', text: '物料名称', dictCode: '' })
        fieldList.push({ type: 'string', value: 'brand', text: '品牌', dictCode: '' })
        fieldList.push({ type: 'string', value: 'specification', text: '规格型号', dictCode: '' })
        fieldList.push({ type: 'int', value: 'amount', text: '数量', dictCode: '' })
        fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: '' })
        fieldList.push({ type: 'BigDecimal', value: 'referencePrice', text: '参考价格', dictCode: '' })
        this.superFieldList = fieldList
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            if (this.dataSource && this.dataSource.length) {
              // 判断是否含有定标意见单
              if (this.dataSource[0].opinionId) {
                this.$emit('isShowBtn', true)
              } else {
                this.$emit('isShowBtn', false)
              }
            }
            this.isShowAdd()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          // this.showAdd = false
          this.purchaseInfoBack([])
          this.isShowAdd()
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          if (item.opinionId) {
            this.$emit('purchaseInfoBack', item.opinionId)
          }
          item.key = index
        })
      },
      handleEdit: function (record) {
        // debugger;
        if (!this.teamId) {
          this.$message.error('请选择所属团队!')
          return false
        }
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.dataSource = this.dataSource
        this.$refs.modalForm.teamId = this.teamId
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd: function () {
        if (!this.teamId) {
          this.$message.error('请选择所属团队!')
          return false
        }
        this.$refs.modalForm.add()
        this.$refs.modalForm.dataSource = this.dataSource
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.teamId = this.teamId
        this.$refs.modalForm.disableSubmit = false
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          // 若第一条数据项目被修改，则后面数据会被删除
          if (data.key == 0) {
            if (this.dataSource[0].projectId != data.projectId) {
              // 清空其他数据
              this.dataSource = [data]
              this.purchaseInfoBack(this.dataSource)
              this.isShowAdd()
              return false
            }
          }
          this.dataSource.splice(data.key, 1, data);
        }
        this.purchaseInfoBack(this.dataSource)
        this.isShowAdd()
      },
      purchaseInfoBack (arr = []) {
        if (arr && arr.length) {
          arr.forEach((item) => {
            if (item.opinionId) {
              this.$emit('purchaseInfoBack', item.opinionId)
            } else {
              this.$emit('purchaseInfoBack', '')
            }
          })
        } else {
          this.$emit('purchaseInfoBack', '')
        }
      },
      // 判断按钮的显隐
      isShowAdd () {
        // 迭代版升级1判断列表第一个是否有项目id，有则显示新增按钮，没有则隐藏新增按钮
        if (this.dataSource && this.dataSource.length) {
          if (this.dataSource[0].projectId) {
            // 显示新增按钮
            this.showAdd = false
          } else {
            // 隐藏新增按钮
            this.showAdd = true
          }
        } else {
          // 显示新增按钮
          this.showAdd = false
        }
      },
      submitForm() {
        return this.dataSource
      },
      onDetails(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },
      onOpinionDetails (id) {
        this.$refs.opinionInputModal.visible = true
        this.$nextTick(() => {
          this.$refs.opinionInputModal.loadData(id)
        })
        
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
